package com.fast.user.web.mobile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fast.base.db.page.PageView;
import com.fast.base.db.sql.impl.SqlGeneratorImpl;
import com.fast.base.model.AnoSysLog;
import com.fast.base.util.DateUtils;
import com.fast.base.util.LogUtils;
import com.fast.base.util.data.MathUtils;
import com.fast.base.util.web.IPUtils;
import com.fast.base.util.web.ResponseData;
import com.fast.base.util.web.ResponseEnum;
import com.fast.base.web.BaseController;
import com.fast.cms.constant.CommonConstant;
import com.fast.common.userCache.MemberCacheUtils;
import com.fast.common.userCache.UserRequestUtils;
import com.fast.user.constant.LoginTypeEnum;
import com.fast.user.dto.CommonLoginDTO;
import com.fast.user.model.member.BrowseMemberInfo;
import com.fast.user.model.member.DeliveryAddress;
import com.fast.user.model.member.Member;
import com.fast.user.service.member.MemberService;
import com.fast.user.web.form.mobile.MemberListForm4Mobi;
import com.fast.user.web.form.web.BrowerRecordsForm;
import com.fast.user.web.form.web.DeliveryAddressForm;
import com.fast.user.web.form.web.DeliveryAddressListForm;
import com.fast.user.web.form.web.MemberListForm;
import com.fast.user.web.form.web.ModifyMemberInfoForm;
import com.fast.user.web.form.web.SendBrowerRecordsForm;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;


/**
 * ClassName:MemberController <br/>
 * 用途:Member信息控制处理 <br/>
 * 开发人员：lushuifa http://lushuifa.iteye.com/ 
 * 邮箱:lsflu@126.com
 * @version
 * @since JDK 1.6
 * @see Date: 2016年11月30日 14时51分41秒 <br/>
 */
@Api(value="member",tags={"member web interface"})
@Controller("AppMemberController")
@RequestMapping("/app/member")
public class AppMemberController extends BaseController{
	
	@Resource(name="memberService")
	private MemberService memberService;
	
	/**
	 * 说明: app手机端手机注册<br>
	 * 编写者:lushuifa
	 * 创建时间:2018年8月10日 下午9:55:22 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@RequestMapping(value="/memberRegist",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("会员手机号注册")
    @ApiImplicitParams({
    	 @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String",paramType = "query"),
    	 @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String",paramType = "query"),
    	 @ApiImplicitParam(name = "verifyCode", value = "手机验证码", required = true, dataType = "String",paramType = "query"),
    	 @ApiImplicitParam(name = "sourceType", value = "注册来源:0.android 1.IOS", required = true, dataType = "String",paramType = "query")
    	 })
	public ResponseData memberRegist(
			@RequestParam(required=true) String mobile, 
			@RequestParam(required=true) String password,
			@RequestParam(required=true) String verifyCode,
			@RequestParam(required=true) int sourceType){
		LogUtils.info("mobileRegist.mobile:"+mobile+",verifyCode:"+verifyCode);
		ResponseData responseData = new ResponseData();
		try {
			//校验手机验证码
			String sessionMobileCode = (String) webUtil.getSessionAttr(CommonConstant.APP_MOBILECODE_SESSION_KEY);
			if(!StringUtils.equals(sessionMobileCode, verifyCode)){
				responseData.buildResult(ResponseEnum.CAPTCHA_FAILD);
				return responseData;
			}
			//入库操作
			Member member = new Member();
			String loginName = "E"+MathUtils.getTheOnlyStr();
			member.setNickName(loginName);
			member.setUuid(MathUtils.getTheOnlyStr());
			member.setMobile(mobile);
			member.setPassword(password);
			member.setLocked(0);
			//注册，创建，编辑信息
			member.setEditTime(Calendar.getInstance().getTime());
			member.setCreateTime(Calendar.getInstance().getTime());
			member.setRegDateTime(new Date());
			member.setRegIp(webUtil.getIpAddr());
			member.setRegAddress(IPUtils.getAddress("ip="+webUtil.getIpAddr(), "utf-8"));
			Member curMember = this.memberService.merge(member);
			if(curMember!=null){
				webUtil.setSessionAttr("member",curMember);
				String cookieV = URLEncoder.encode(JSONObject.toJSONString(member), "UTF-8");
				Cookie cookie = new Cookie("curMember",cookieV);
				cookie.setMaxAge(60*60*24);
				responseData = ResponseData.buildSuccessResponse();
			}
		} catch (Exception e) {
			responseData.failue();
			e.printStackTrace();
		}
		return responseData;
	}
	
	/**
	 * 登录
	 * @param loginName
	 * @param password
	 * @param loginType 
	 * 0 普通登录 
	 * 2 微信登录
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/login.do",method = RequestMethod.POST)
	@ApiOperation("会员APP端登录")
    @ApiImplicitParams({
    	 @ApiImplicitParam(name = "loginName", value = "用户名/手机号/邮箱", required = true, dataType = "String",paramType = "query"),
    	 @ApiImplicitParam(name = "password", value = "密码需要提前：SHA256加密,如6个8的加密值是:92925488b28ab12584ac8fcaa8a27a0f497b2c62940c8f4fbc8ef19ebc87c43e", required = true, dataType = "String",paramType = "query"),
    	 @ApiImplicitParam(name = "loginType", value = "登录类型:0普通登录、1、微信登录", required = true, dataType = "String",paramType = "query"),
    	 })
	public ResponseData login(
			@RequestParam(required=true) String loginName,
			@RequestParam(required=true) String password,
			@RequestParam(required=true) int loginType){
		LogUtils.info("login_loginName:"+loginName+",password:"+password+",loginType:"+loginType);
		ResponseData responseData = new ResponseData();
		try {
			//普通登录
			if(loginType==LoginTypeEnum.member.getCode()) {
				Member member = this.memberService.login(loginName, password);
				if(null!=member) {
					CommonLoginDTO commonLoginDto = new CommonLoginDTO();
					commonLoginDto.setLoginName(loginName);
					commonLoginDto.setRealName(member.getRealName());
					commonLoginDto.setLoginType(loginType);
					commonLoginDto.setUserId(member.getUuid());
					responseData.setData(commonLoginDto);
					LogUtils.info("login_member_result:"+responseData);
					return responseData;
				}else {
					responseData.buildResult(ResponseEnum.USER_NULL);
					LogUtils.info("login_member_result:"+responseData);
					return responseData;
				}
			//微信登录
			}else if(loginType==LoginTypeEnum.wexin.getCode()) {
				
			}else {
				responseData.buildResult(ResponseEnum.FAILURE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		LogUtils.info("logn.responseData:"+responseData.toString());
		return responseData;
	}
	
	/**
	 * 通过手机验证码登录
	 * @param mobile
	 * @param verifyCode 手机验证码
	 * @return
	 */
	@RequestMapping(value="/memberLoginByVerifyCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("通过手机验证码登录")
	public ResponseData memberLoginByVerifyCode(String mobile,String verifyCode){
		LogUtils.info("memberLogin.mobile:"+mobile+",verifyCode:"+verifyCode);
		ResponseData responseData = new ResponseData();
		try {
			//校验手机验证码
			String sessionMobileCode = (String) webUtil.getSessionAttr(CommonConstant.APP_MOBILECODE_SESSION_KEY);
			if(!StringUtils.equals(sessionMobileCode, verifyCode)){
				responseData.buildResult(ResponseEnum.CAPTCHA_FAILD);
				return responseData;
			}
			Member member = this.memberService.queryMemberByMobile(mobile);
			if(member.getLocked()==0){
				member.setLoginIp(webUtil.getIpAddr());
				member.setLoginDateTime(DateUtils.getNow());
				member.setLoginCount(member.getLoginCount()+1);
				String updateSql = "update "+SqlGeneratorImpl.getTableName(Member.class)+" set loginIp='"+webUtil.getIpAddr()+"',loginDateTime='"+DateUtils.getNow()+"',loginCount=loginCount+1 where id="+member.getId();
				this.memberService.modifyRow(updateSql);
				//改变登录次数
				int newCount = this.memberService.increaseLoginCount(member.getId());
				member.setLoginCount(newCount);
				if(!member.getHeadImageUrl().equals("")){
					member.setHeadImageUrl(getImgPath()+member.getHeadImageUrl());
				}
				responseData.setData(member);
				webUtil.setSessionAttr("member",member);
			} else {
				responseData.buildResult(ResponseEnum.USER_HAS_LOCKED);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 获取邮寄地址列表
	 * @param deliveryAddressListForm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/queryDeliveryAddressList.do", method=RequestMethod.POST)
	@ApiOperation("获取邮寄地址列表")
	public ResponseData queryDeliveryAddressList(DeliveryAddressListForm deliveryAddressListForm){
		ResponseData responseData = new ResponseData();
		Map<String,Object> gridMap = new HashMap<String,Object>();
		PageView<DeliveryAddress> pageView = new PageView<DeliveryAddress>();
		try {
			pageView = this.memberService.queryDeliveryAddressList(deliveryAddressListForm);
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
			responseData.setData(gridMap);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 保存或更新邮寄地址
	 * @param deliveryAddressForm
	 * @return
	 */
	@RequestMapping(value="/saveOrUpdateDeliveryAddress.do",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("客户端保存邮寄地址")
	public ResponseData saveOrUpdateDeliveryAddress(DeliveryAddressForm deliveryAddressForm){
		ResponseData responseData = new ResponseData();
		DeliveryAddress deliveryAddress = null;
		try {
			String uuid = deliveryAddressForm.getUuid();
			if(StringUtils.isNotBlank(uuid)){
				deliveryAddress = this.memberService.queryForBeanByUUID(DeliveryAddress.class,uuid);
				BeanUtils.copyProperties(deliveryAddress, deliveryAddressForm);
			}else{
				deliveryAddress = new DeliveryAddress();
				BeanUtils.copyProperties(deliveryAddress, deliveryAddressForm);
				UserRequestUtils.bindCreaterInfo(deliveryAddress);
			}
			UserRequestUtils.bindEditorInfo(deliveryAddress);
			if(this.memberService.merge(deliveryAddress)!=null){
				responseData.buildResult(ResponseEnum.EDIT_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.EDIT_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 获取（发过我）列表  分页方式获取
	 * @param browerRecordsForm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getBrowerRecords.do", method=RequestMethod.POST)
	@ApiOperation("获取互看记录列表")
	public ResponseData getBrowerRecords(BrowerRecordsForm browerRecordsForm){
		ResponseData responseData = new ResponseData();
		Map<String,Object> gridMap = new HashMap<String,Object>();
		PageView<BrowseMemberInfo> pageView = new PageView<BrowseMemberInfo>();
		try {
			pageView = this.memberService.getBrowerRecords(browerRecordsForm);
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
			responseData.setData(gridMap);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 保存看过我的数据
	 * @param sendBrowerRecordsForm
	 * @return
	 */
	@ResponseBody
	@RequestMapping(path={"/sendBrowerRecords.do"},method = RequestMethod.POST)
	@ApiOperation("保存互看记录")
	public ResponseData sendBrowerRecords(SendBrowerRecordsForm sendBrowerRecordsForm) {
		ResponseData responseData = new ResponseData();
		try {
			BrowseMemberInfo browseMemberInfo = new BrowseMemberInfo();
			BeanUtils.copyProperties(browseMemberInfo, sendBrowerRecordsForm);
			browseMemberInfo.setUuid(MathUtils.getTheOnlyStr());
			if(this.memberService.merge(browseMemberInfo)!=null){
				responseData.setMsg("操作成功");
				responseData.setData(browseMemberInfo);
			}
			responseData.setCode("00");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 编辑会员信息，资料补充
	 * @param actionType
	 * @param headPic
	 * @return
	 */
	@ResponseBody
	@RequestMapping(path={"/modifyMemberInfo.do"},method = RequestMethod.POST)
	@ApiOperation("编辑会员信息，资料补充")
	public ResponseData modifyMemberInfo(ModifyMemberInfoForm modifyMemberInfoForm) {
		Member member = null;
		ResponseData responseData = new ResponseData();
		try {
			String userId =  modifyMemberInfoForm.getUserId();
			if(StringUtils.isNotBlank(userId)){
				member = this.memberService.queryForBeanByUUID(Member.class,userId);
				BeanUtils.copyProperties(member, modifyMemberInfoForm);
				UserRequestUtils.bindEditorInfo(member);
				if(this.memberService.merge(member)!=null){
					responseData.setMsg("操作成功");
					responseData.setData(member);
				}
				responseData.setCode("00");
			}else {
				responseData.buildResult(ResponseEnum.USER_ID_IS_NULL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	
	/**
	 * 拿到当前登录的信息
	 * @param user 用户对象
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getMemberInfo.do",method = RequestMethod.POST)
	@ApiOperation("拿到当前登录的信息")
	@ApiImplicitParams({
	   	  @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "String",paramType = "query"),
	   	 })
	public ResponseData getMemberInfo(String userId){
		ResponseData responseData = new ResponseData();
		try {
			Member member = this.memberService.getMemberByUUID(userId);
			if(null!=member){
				responseData.setData(member);
			}else{
				responseData.failue();
				return responseData;
			}
		}catch (Exception e) {
			LogUtils.info("getAdminInfo.err.登录异常：", e);
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 得到[Member]列表
	 * @throws IOException 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getMemberList.do", method=RequestMethod.POST)
	@ApiOperation("会用户列表,保留接口")
	public ResponseData getMemberList(MemberListForm4Mobi memberListForm4Mobi){
		ResponseData responseData = new ResponseData();
		Map<String,Object> gridMap = new HashMap<String,Object>();
		PageView<Member> pageView = new PageView<Member>();
		try {
			MemberListForm memberListForm = new MemberListForm();
			BeanUtils.copyProperties(memberListForm, memberListForm4Mobi);
			pageView = this.memberService.getMemberListByPage(memberListForm );
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
			responseData.setData(gridMap);
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * app手机端登录操作
	 * @param loginName 登录名或手机号
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/memberLogin.do",method = RequestMethod.POST)
    @ResponseBody
    @AnoSysLog(actionName="手机端登录")
	@ApiIgnore
	public ResponseData memberLogin(String loginName,String password){
		LogUtils.info("memberLogin.mobile :"+loginName+",password:"+password);
		ResponseData responseData = new ResponseData();
		try {
			//核实用户名在数据中是否存在
			boolean isExist = memberService.isExistUser(loginName);
			if(isExist){
				Member member = memberService.login(loginName,password);
				if (member != null) {
					if(member.getLocked()==0){
						member.setLoginIp(webUtil.getIpAddr());
						member.setLoginDateTime(DateUtils.getNow());
						member.setLoginCount(member.getLoginCount()+1);
						String updateSql = "update "+SqlGeneratorImpl.getTableName(Member.class)+" set loginIp='"+webUtil.getIpAddr()+"',loginDateTime='"+DateUtils.getNow()+"',loginCount=loginCount+1 where id="+member.getId();
						this.memberService.modifyRow(updateSql);
						//改变登录次数
						int newCount = this.memberService.increaseLoginCount(member.getId());
						member.setLoginCount(newCount);
						if(!member.getHeadImageUrl().equals("")){
							member.setHeadImageUrl(getImgPath()+member.getHeadImageUrl());
						}
						responseData.setData(member);
						webUtil.setSessionAttr("member",member);
					} else {
						responseData.buildResult(ResponseEnum.USER_HAS_LOCKED);
					}
				}else{
					responseData.buildResult(ResponseEnum.PASSWORD_FAILD);
				}
			}else{
				responseData.buildResult(ResponseEnum.USER_NULL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 发送手机验证码
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value="/sendMobileVerifyCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("发送手机验证码")
	@ApiImplicitParams({
   	  @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String",paramType = "query"),
   	  @ApiImplicitParam(name = "sendType", value = "发送类型:findPsd 找回密码  simple 普通验证码模式", required = true, dataType = "String",paramType = "query"),
   	 })
	public ResponseData sendMobileVerifyCode(String mobile,String sendType){
		LogUtils.info("sendMobileVerifyCode.mobile:"+mobile);
		ResponseData responseData = new ResponseData();
		try {
			if(sendType.equals("findPsd")){
				boolean isExist = this.memberService.existMobile(mobile);
				if(!isExist){
					responseData.buildResult(ResponseEnum.MOBILE_NOT_EXISTS);
					return responseData;
				}
			}
			//发送短信
			String mobileCode = this.memberService.sendMobileCode(mobile,sendType);
			if(StringUtils.isNotEmpty(mobileCode)){
				JSONObject jo = new JSONObject();
				jo.put("mobileVerifyCode", mobileCode);
				webUtil.setSessionAttr(CommonConstant.APP_MOBILECODE_SESSION_KEY,mobileCode);
				responseData.buildSuccessResponse();
			}else{
				responseData.failue();
			}
		} catch (Exception e) {
			responseData.failue();
			e.printStackTrace();
		}
		return responseData;
	}
	
	
	
	/**
	 * app手机端修改密码操作
	 * @param userName
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/updateLoginPassword",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("app手机端修改密码操作")
	@ApiImplicitParams({
	   	  @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String",paramType = "query"),
	   	  @ApiImplicitParam(name = "password", value = "密码,请加密后再传输,SHA256", required = true, dataType = "String",paramType = "query"),
	   	  @ApiImplicitParam(name = "newPassword", value = "新密码,请加密后再传输,SHA256", required = true, dataType = "String",paramType = "query"),
	   	 })
	public ResponseData updateLoginPassword(@RequestParam(name="mobile",required=true) String mobile,
			@RequestParam(name="password",required=true) String password,
			@RequestParam(name="newPassword",required=true) String newPassword){
		LogUtils.info("updateLoginPassword.mobile:"+mobile);
		Member member = MemberCacheUtils.getLoginMember();
		ResponseData responseData = new ResponseData();
		try {
			if(ObjectUtils.notEqual(member, null)){
				responseData = this.memberService.updatePassword(member.getId(), newPassword);
			}else{
				responseData.buildResult(ResponseEnum.USER_NOT_LOGIN);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
}
